<template>
  <div class="page">
    <!-- banner 开始 -->
    <div class="banner">
      <img src="@/assets/images/v70/banner.jpg" alt="">
      <img src="@/assets/images/v70/04.jpg" alt="">
    </div>
    <!-- banner 开始 -->

    <!-- 借款 开始 -->
    <div class="loan_box">
      <!-- <img src="@/assets/images/nov/line_top.png" class="line_top" alt="" /> -->
      <div class="loan_inner">

        <div class="top_input">
          <div class="input_box">
            <span>￥</span>
            <input type="tel" v-model="amount" class="a_input" maxlength="6" @input="onInput" />
            <span></span>
          </div>
          <div class="input_tips">试算金额<span>(点击修改)</span></div>
        </div>

        <div class="menu_box">
          <div class="menu_row">
            <span class="name">借款期限</span>
            <div class="cell_list">
              <van-button :plain="active == item ? false : true" size="small" :type="active == item ? 'info' : 'default'"
                v-for="(item, index) in list" :key="index" class="btn" @click="onClick(item)">{{ item }}期</van-button>
            </div>
          </div>

          <div class="menu_row">
            <span class="name">每期应还</span>
            <div class="cell_list">￥{{ monthPay }}</div>
          </div>

          <div class="menu_row">
            <span class="name">优惠总还</span>
            <div class="cell_list">￥{{ total }}</div>
          </div>
        </div>
        <!-- <h4 class="tips">
          *年化费率按照最低<span>6%</span>试算，具体以审核结果为准
        </h4> -->

        <h2 class="h2">【填写真实信息，有助于贷款成功！】</h2>

        <!-- 单行数据 开始 -->
        <div class="row">
          <div class="input_box">
            <input type="text" v-model="form.name" placeholder="姓名" class="a_input" />
          </div>
          <div class="sex_box">
            <van-radio-group v-model="form.gender" direction="horizontal">
              <van-radio :name="1" checked-color="#ff8139">先生<template #icon="props">
                  <img class="img_icon" :src="props.checked ? activeIcon : inactiveIcon" />
                </template></van-radio>
              <van-radio :name="2" checked-color="#ff8139">女士<template #icon="props">
                  <img class="img_icon" :src="props.checked ? activeIcon : inactiveIcon" />
                </template></van-radio>
            </van-radio-group>
          </div>
        </div>
        <!-- 单行数据 end -->

        <!-- 单行数据 开始 -->
        <div class="row">
          <div class="input_box">
            <input type="tel" v-model="form.mobile" maxlength="11" placeholder="手机号码" class="a_input" />
          </div>
        </div>
        <!-- 单行数据 end -->

        <!-- 单行数据 开始 -->
        <div class="row">
          <div class="input_box">
            <input type="text" v-model="form.code" maxlength="6" placeholder="短信验证码" class="a_input" />
          </div>
          <div class="sex_box">
            <van-button type="info" size="small" class="code_btn" @click="sendCode" :disabled="time > 0">{{ time > 0 ?
              time + "重新获取" : "点击获取" }}</van-button>
          </div>
        </div>
        <!-- 单行数据 end -->

        <div v-show="showMore">
          <!-- 单行数据 开始 -->
          <div class="row">
            <span class="name">请选择您的年龄</span>
            <div class="input_box selct_box" @click="openDialog">
              <span class="selct_view">{{
                form.age ? form.age + "岁" : "请选择"
              }}</span>
              <van-icon name="arrow-down" color="#ff8139" />
            </div>
          </div>
          <!-- 单行数据 end -->

          <!-- 工作所在地 开始 -->
          <div class="title">工作所在地</div>
          <div class="city_list">
            <div class="cell" v-for="(item, index) in cityList" :key="index">
              <div class="cell_in" :class="address == item ? 'active' : ''" @click="chooseAddress(item)">
                {{ item }}
              </div>
            </div>
          </div>
          <!-- <p style="color:#f00;">金融机构不接受【{{cityList[0].name}}】以外城市申请</p> -->
          <!-- 工作所在地 end -->

          <!-- 完善信息快速审核（可多选） 开始 -->
          <div class="title">完善信息快速审核（可多选）</div>
          <div class="city_list info_list">
            <div class="cell" v-for="(item, index) in infoList" :key="index">
              <div class="cell_in" :class="form[item.id] ? 'active' : ''" @click="chooseInfo(item)">
                {{ item.name }}
              </div>
            </div>
          </div>
          <!-- 完善信息快速审核（可多选） end -->
        </div>

        <!-- 立即申请 开始 -->
        <div class="btn_group">
          <van-button size="large" class="apply_btn" type="info" @click="apply" :loading="loading">立即申请</van-button>
        </div>
        <!-- 立即申请 end -->

        <!-- 协议 开始 -->
        <div class="xiyi_box">
          <van-checkbox v-model="checked" checked-color="#ff8139" icon-size="16">我已阅读并同意<span
              @click.stop="lookContract">用户服务及隐私协议</span><template #icon="props">
                  <img class="img_icon" :src="props.checked ? activeIcon : inactiveIcon" />
                </template></van-checkbox>
        </div>
        <!-- 协议 end -->

        <div class="tips_box">*我们郑重承诺：以上信息严格保密</div>

      </div>
    </div>
    <!-- 借款 end -->

    <!-- 底部 开始 -->
    <div class="footer_box">
      <img src="@/assets/images/v70/03.jpg" class="footer_img" alt="" />
      <p>摩尔龙集团</p>
      <p>Copyright 2009-2021 Edai Corporation All Rights Reserved.</p>
      <p>四川易贷网金融信息服务有限公司 版权所有</p>
      <p>摩尔龙贷款代办服务</p>
      <p>温馨提示:</p>
      <p>贷款有风险 借贷需谨慎</p>
      <p>请根据个人能力合理贷款，理性消费，避免逾期.</p>
      <p>贷款额度、放款时间等以实际审批为准</p>
      <p>年化利率3.6%-12%(单利)</p>
      <p>合作机构:平安银行 2020.09.07-长期</p>
      <p>温馨提示:公积金相关资料仅作为贷款服务验资证明.</p>
      <p>放款路径与公积金账户无关</p>
      <p>备案号: 蜀ICP备16029964号</p>
    </div>
    <!-- 底部 end -->

    <!-- 弹框 开始 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-picker show-toolbar :columns="ageList" @confirm="onConfirm" @cancel="closeDialog" />
    </van-popup>
    <!-- 弹框 end -->

    <!-- 确认城市弹框 开始 -->
    <van-dialog v-model="showDialog" title="提示" show-cancel-button @confirm="submit()" :before-close="beforeClose">
      <div class="van_dialog">
        <h2 class="h2">为了更好的为您服务，请问您的常驻城市是？</h2>
        <div class="city_list_box">
          <van-button class="van_button" size="small" v-for="(item, index) in confirmList" :key="index"
            :type="confirmCity == item ? 'info' : 'default'" @click="chooseCity(item)">{{ item }}</van-button>
        </div>
      </div>
    </van-dialog>
    <!-- 确认城市弹框 end -->

    <!-- 协议确认弹框 开始 -->
    <van-dialog v-model="xieyiDialog" title="提示" show-cancel-button @confirm="confirmEvent"
      @cancel="cancelEvent('xieyiDialog')">
      <div class="agreement_box">
        <agreement-contract></agreement-contract>
      </div>
    </van-dialog>
    <!-- 协议确认弹框 开始 -->

    <!-- 成功弹框 开始 -->
    <van-popup v-model="successDialog" class="van_popup" position="center" round>
      <div class="popup_result_box">
        <div class="inner">
          <h2 class="h2">您的贷款申请成功</h2>
          <h3 class="h3">2小时内将有审核专员与您联系放款事宜</h3>
          <h4 class="h4">请保持电话畅通</h4>
          <h5 class="h5">以免影响您的资金使用</h5>
        </div>
        <div class="btn_group">
          <button class="btn" @click="cancelEvent('successDialog')">关闭</button>
        </div>
      </div>
    </van-popup>
    <!-- 成功弹框 开始 -->

  </div>
</template>

<script>
import {
  MARKETINGADD,
  GETIPINFO,
  GETCODE,
  GETMOBILEADDRESS,
  SAVEINFO,
  GETONECITY,
  SENDMARKETINGREPORTING,
} from "@/http/nov";
import {
  RadioGroup,
  Radio,
  Checkbox,
  Grid,
  GridItem,
  Toast,
  Dialog,
  Button,
  Popup,
  Picker,
  Icon,
} from "vant";
import { checkPhone, getUrlParams } from "@/common/util";
import AgreementContract from "@/components/agreement.vue";
export default {
  components: {
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Checkbox.name]: Checkbox,
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Dialog.Component.name]: Dialog.Component,
    [Icon.name]: Icon,
    AgreementContract,
  },
  data() {
    return {
      list: [12, 24, 36, 60, 96],
      active: 12,
      radio: 1,
      cityList: [],
      address: "",
      infoList: [
        // { name: "有工资", id: "getwayIncome", value: 1 },
        { name: "本地商品房", id: "house", value: 1 },
        { name: "本地公积金", id: "publicFund", value: 1 },
        { name: "有企业缴税", id: "company", value: 1 },
        { name: "有15万以上私家车", id: "car", value: 1 },
        { name: "有5万以上信用卡额度", id: "creditCard", value: 1 },
      ],
      infoActive: "",
      checkList: {},
      checked: false,
      amount: 200000,
      monthPay: 0,
      total: 0,
      form: {
        gender: 1,
      },
      ageList: [],
      showPopup: false,
      time: 0,
      showMore: false,
      ipCity: "",
      confirmList: [],
      showDialog: false,
      confirmCity: "",
      loading: false,
      applyInfo: {},
      adId: "",
      currentCity: "",
      xieyiDialog: false,
      aptitude: [],
      successDialog: false,

      mobileCity: "", // 手机归属地
      activeIcon: require('@/assets/images/v70/gou_active.png'),
      inactiveIcon: require('@/assets/images/v70/gou.png')
    };
  },
  mounted() {
    this.getCity();
    this.send();
    this.getIp();
    this.calculate();

    let arr = [];
    for (let i = 25; i <= 55; i++) {
      arr.push(i);
    }
    this.ageList = arr;
  },
  methods: {
    /** 选择借款期数 */
    onClick(e) {
      this.active = e;
      this.calculate();
    },

    /** 选择工作地 */
    chooseAddress(e) {
      this.address = e;
    },

    /** 选择信息 */
    chooseInfo(row) {
      let id = row.id;
      let o = this.form;
      let arr = this.aptitude || [];
      if (o[id]) {
        this.$set(this.form, id, "");
        arr = arr.filter((k) => k != row.name);
      } else {
        this.$set(this.form, id, 1);
        arr.push(row.name);
      }
      console.log(arr)
      this.aptitude = arr;
    },

    /** 选择以上皆无 */
    hasNothing() {
      let o = this.form;
      o.company = 2;
      o.getwayIncome = 2;
      o.house = 2;
      o.insurance = 2;
      o.publicFund = 2;
      o.car = 2;
      this.$set(this, "form", o);
      this.infoActive = 1;
    },

    /** 获取城市列表 */
    getCity() {
      let _this = this;
      let oParams = {};
      oParams.cityCode = this.$route.query.city;
      GETONECITY(oParams).then((res) => {
        console.log(res);
        let obj = res.data || "";

        _this.cityList = obj;
        _this.currentCity = obj.slice(0, obj.length - 1);
      });
    },

    /** 进入首页 埋点 */
    send() {
      let _this = this;
      let o = getUrlParams();
      let oParams = {};
      let base64 = this.toBase64();
      oParams.accountId = o.accountId;
      oParams.channel = o.channel;
      oParams.urlBase64 = base64;
      oParams.clickId = o.gdt_vid;
      console.log(oParams);
      MARKETINGADD(oParams).then((res) => {
        if (res.code != 0) {
          Toast(res.message || res.msg || "出错了，请联系管理员");
          return false;
        }
        _this.adId = res.o;
      });
    },

    /** 获取base64 */
    toBase64() {
      let url = window.location.href;
      let n = encodeURI(url);
      var base64 = btoa(n);
      return base64;
    },

    /** 获取ip */
    getIp() {
      let _this = this;
      GETIPINFO().then((res) => {
        console.log(res);
        if (res.code != 0) {
          Toast(res.message || res.msg || "出错了，请联系管理员");
          return false;
        }
        let obj = res.o || {};
        _this.ipCity = obj.city;
      });
    },

    /** 计算 */
    calculate() {
      let o = Number(this.amount);
      let m = Number(this.active);
      console.log(o);
      if (!o) {
        this.monthPay = 0;
        this.total = 0;
        return false;
      }

      //每期应还
      let mPay = ((o * 6) / 100 + o) / m;

      //到期总还
      let n = (6 * (m / 12)) / 100;
      let total = o * (1 + n);
      this.monthPay = mPay.toFixed(2);
      this.total = Number(total).toFixed(2);
    },

    /** 监听贷款金额输入 */
    onInput(e) {
      this.calculate();
    },

    /** 获取短信验证码 */
    sendCode() {
      let that = this;
      let time = 60;
      let o = this.form.mobile;
      if (!o) {
        Toast("请输入手机号码");
        return false;
      }

      if (!checkPhone(o)) {
        Toast("手机号码格式不正确");
        return false;
      }

      let m = setInterval(function () {
        if (time == 0) {
          clearInterval(m);
          that.time = "";
          return false;
        }
        time--;
        that.time = time--;
      }, 1000);

      this.showMore = true;
      this.getMobileAddress();
      GETCODE({ mobile: o }).then((res) => {
        console.log(res);
        // if (res.code != 0) {
        Toast(res.message || res.msg || "出错了，请联系管理员");
        //   return false;
        // }
        //that.form.code = res.data;
      });
    },

    /** 选择年纪 */
    onConfirm(e) {
      console.log(e);
      this.form.age = e;
      this.closeDialog();
    },

    /** 打开弹框 */
    openDialog() {
      this.showPopup = true;
    },

    /** 关闭弹框 */
    closeDialog() {
      this.showPopup = false;
    },

    /** 立即申请 */
    apply() {
      let _this = this;
      let o = this.form;
      if (!this.amount) {
        Toast("请输入贷款金额");
        return false;
      }
      if (Number(this.amount) < 30000) {
        Toast("金融机构不接受3万以下申请");
        return false;
      }
      if (!o.name) {
        Toast("请输入姓名");
        return false;
      }

      if (!o.name) {
        Toast("请输入姓名");
        return false;
      }

      if (!o.mobile) {
        Toast("请输入手机号码");
        return false;
      }

      if (!checkPhone(o.mobile)) {
        Toast("手机号码格式不正确");
        return false;
      }

      if (!o.code) {
        Toast("请输入验证码");
        return false;
      }

      if (!o.age) {
        Toast("请选择年龄");
        return false;
      }

      if (!this.address) {
        Toast("请选择工作所在地");
        return false;
      }

      if (
        !o.publicFund &&
        !o.company &&
        !o.house &&
        !o.car &&
        !o.creditCard
      ) {
        Toast("请选择完善信息");
        return false;
      }

      if (!this.checked) {
        this.xieyiDialog = true;
        return false;
      }

      let m = getUrlParams();
      let oParams = JSON.parse(JSON.stringify(o));
      oParams.channel = m.channel;
      oParams.loanAmount = this.amount;
      oParams.city = this.address;
      console.log(oParams);

      // 选中的城市都一致
      _this.loading = true;
      _this.applyInfo = oParams;
      //_this.submit(oParams);

      //return false;

      let arr = _this.judageCity();

      // 选中的城市都一致
      _this.loading = true;
      if (!arr || arr.length <= 0) {
        _this.submit(oParams);
      } else {
        _this.showDialog = true;
        _this.confirmList = arr;
        _this.applyInfo = oParams;
        _this.loading = false;
      }
      return false;
    },

    /** 提交信息 */
    submit(options) {
      let _this = this;
      let oParams = this.applyInfo;
      if (options) {
        oParams = options;
      }
      oParams.mid = this.adId;
      oParams.aptitude = this.aptitude.toString();
      console.log(oParams);
      // if (!options && !this.confirmCity) {
      //   Toast("请选择常驻城市");
      //   return false;
      // }

      // if (!options) {
      //   oParams.city = this.confirmCity;
      // }
      SAVEINFO(oParams).then((res) => {
        _this.loading = false;
        if (res.code != 0) {
          Toast(res.message || res.msg || "出错了，请联系管理员");
          return false;
        }
        _this.toReport();
        //_this.$router.push({ name: "result" });
        _this.showDialog = false;
        _this.successDialog = true;
      });
      return false;
    },

    /** 获取手机号码归属地 */
    getMobileAddress() {
      let _this = this;
      let oParams = {};
      oParams.mobile = _this.form.mobile;
      GETMOBILEADDRESS(oParams).then((res) => {
        let nm = res.City || "";
        if (nm && nm[nm.length - 1] != "市") {
          nm = nm + "市";
        }
        _this.mobileCity = nm;
      });
    },

    /** 判断地址 */
    judageCity() {
      let _this = this;
      let list = this.cityList;
      let ic = this.ipCity; //ip所在城市
      let mc = this.mobileCity; //手机归属地所在城市
      let c = _this.address; //选中的城市
      let arr = [];

      // ip所在城市是否包含选中城市
      let ipHas = ic.indexOf(c) >= 0;

      // 手机归属地是否包含选中城市
      let mobileHas = mc.indexOf(c) >= 0;
      console.log('ipHas', ipHas)
      console.log('mobileHas', mobileHas)
      if (!ipHas && !mobileHas) {
        arr.push(ic);
        arr.push(mc);
        arr.push(c);
      }
      console.log(arr)
      let newArray = Array.from(new Set(arr));
      console.log(newArray);
      return newArray;
    },

    /** 选择城市 */
    chooseCity(item) {
      console.log(item);
      this.confirmCity = item;
      this.address = item;
      this.applyInfo.city = item;
    },

    /** 关闭弹框 */
    beforeClose(action, done) {
      if (action === "confirm") {
        //this.submit('',done);
        done(false);
      } else {
        done();
      }
    },

    /** 广告上报 */
    toReport() {
      let _this = this;
      let o = getUrlParams();
      let oParams = {};
      let base64 = this.toBase64();
      // oParams.accountId = o.accountId;
      // oParams.channel = o.channel;
      // oParams.urlBase64 = base64;
      // oParams.clickId = o.gdt_vid;
      // console.log(oParams);
      oParams.mId = this.adId;
      SENDMARKETINGREPORTING(oParams);
    },

    /** 查看合同 */
    lookContract() {
      //this.$router.push({name:'result'})
      // window.location.href = "http://gdt.daofen100.com/agree/show.html";
      this.xieyiDialog = true;
    },

    //
    confirmEvent() {
      this.checked = true;
      this.apply();
    },

    cancelEvent(id) {
      this[id] = false;
    },
  },
};
</script>

<style lang="less">
html,
body {
  background: #f0f0f0;
}
</style>
<style lang="less" scoped>
@import "@/assets/styles/v70.less";
</style>
